package com.leyou.item.service.impl;


import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private SpuService spuService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private SpuDetailService spuDetailService;


    @Override
    public PageDTO<SpuDTO> querySpuByPage(Long page, Long rows, Long brandId, Long categoryId, Long id, Boolean saleable) {
        return this.spuService.querySpuByPage(page, rows, brandId, categoryId, id, saleable);
    }

    @Override
    public SpuDTO querySpuById(Long id) {
        return new SpuDTO(this.spuService.getById(id));
    }

    @Override
    public SpuDetailDTO querySpuDetailById(Long id) {
        return new SpuDetailDTO(this.spuDetailService.getById(id));
    }

    @Override
    public List<SkuDTO> listSkuByIds(List<Long> ids) {
        return this.skuService.listSkuByIds(ids);
    }

    @Override
    public List<SkuDTO> listSkuBySpuId(Long id) {
        return skuService.listSkuBySpuId(id);
    }

    // 根据spuId查询spu的所有规格参数值
    @Override
    public List<SpecParamDTO> listSpecParamBySpuId(Long id, Boolean searching) {
        return spuDetailService.listSpecParamBySpuId(id, searching);
    }

    // 根据id查询spu及sku、spuDetail等
    @Override
    public List<SpuDTO> listSpuById(Long id) {
        //查spu
        Spu spu = spuService.getById(id);
        if (spu == null) {
            throw new LyException(400, "商品id不存在！");
        }
        SpuDTO spuDTO = new SpuDTO(spu);
        //查sku
        List<Sku> skuList = skuService.query().eq("spu_id", id).list();
        if (CollectionUtils.isEmpty(skuList)) {
            throw new LyException(400, "商品id不存在！");
        }
        spuDTO.setSkus(SkuDTO.convertEntityList(skuList));
        //查spu detail
        SpuDetail spuDetail = spuDetailService.getById(id);
        if (spuDetail == null) {
            throw new LyException(400, "商品id不存在！");
        }
        spuDTO.setSpuDetail(new SpuDetailDTO(spuDetail));
        return null;
    }

    @Override
    public void updateSpuSaleable(Long id, Boolean saleable) {
        this.spuService.updateSpuSaleable(id, saleable);
    }

    @Override
    public void addGoods(SpuDTO spuDTO) {
        spuService.addGoods(spuDTO);
    }

    @Override
    public void updateGoods(SpuDTO spuDTO) {
        spuService.updateGoods(spuDTO);
    }
}
